<template>
  <AdminLayout title="创建优惠券" subtitle="设计并创建新的优惠券">
    <template #actions>
      <Link :href="route('admin.coupons.index')" 
            class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900">
        ← 返回列表
      </Link>
    </template>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
      <!-- 左侧：表单 -->
      <div class="space-y-8">
        <form @submit.prevent="submitForm" class="space-y-8">
          <!-- 基本信息 -->
          <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-6">基本信息</h3>
            
            <div class="space-y-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">优惠券名称 *</label>
                <input v-model="form.name" type="text" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                       placeholder="例如：新用户专享">
                <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">优惠券代码 *</label>
                <input v-model="form.code" type="text" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                       placeholder="例如：WELCOME10">
                <p v-if="errors.code" class="mt-1 text-sm text-red-600">{{ errors.code }}</p>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">优惠券类型 *</label>
                <select v-model="form.type" required
                        class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
                  <option value="">请选择类型</option>
                  <option value="fixed">立减券</option>
                  <option value="percent">折扣券</option>
                  <option value="shipping">包邮券</option>
                  <option value="full_reduction">满减券</option>
                </select>
                <p v-if="errors.type" class="mt-1 text-sm text-red-600">{{ errors.type }}</p>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">优惠券面值 *</label>
                <input v-model.number="form.value" type="number" step="0.01" min="0" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                       placeholder="例如：10">
                <p class="mt-1 text-sm text-gray-500">
                  {{ getValueDescription(form.type) }}
                </p>
                <p v-if="errors.value" class="mt-1 text-sm text-red-600">{{ errors.value }}</p>
              </div>

              <div v-if="form.type === 'percent'">
                <label class="block text-sm font-medium text-gray-700 mb-2">最大优惠金额</label>
                <input v-model.number="form.max_discount" type="number" step="0.01" min="0"
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                       placeholder="例如：50">
                <p class="mt-1 text-sm text-gray-500">限制折扣券的最大金额</p>
              </div>
            </div>
          </div>

          <!-- 使用条件 -->
          <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-6">使用条件</h3>
            
            <div class="space-y-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">最低消费金额</label>
                <input v-model.number="form.min_purchase" type="number" step="0.01" min="0"
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                       placeholder="例如：100">
                <p class="mt-1 text-sm text-gray-500">0表示无门槛</p>
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">适用范围</label>
                <select v-model="form.applicable_type"
                        class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
                  <option value="all">全场通用</option>
                  <option value="category">指定分类</option>
                  <option value="product">指定商品</option>
                </select>
              </div>

              <!-- 分类选择器 -->
              <div v-if="form.applicable_type === 'category'">
                <label class="block text-sm font-medium text-gray-700 mb-2">选择分类</label>
                <div class="space-y-2 max-h-40 overflow-y-auto border border-gray-300 rounded-md p-3">
                  <div v-for="category in categories" :key="category.id" class="flex items-center">
                    <input 
                      :id="`category-${category.id}`"
                      v-model="selectedCategories" 
                      :value="category.id" 
                      type="checkbox"
                      class="h-4 w-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900"
                    >
                    <label :for="`category-${category.id}`" class="ml-2 text-sm text-gray-700">
                      {{ category.name }}
                    </label>
                  </div>
                </div>
                <p class="mt-1 text-sm text-gray-500">选择适用的商品分类</p>
              </div>

              <!-- 商品选择器 -->
              <div v-if="form.applicable_type === 'product'">
                <label class="block text-sm font-medium text-gray-700 mb-2">选择商品</label>
                <div class="space-y-2 max-h-40 overflow-y-auto border border-gray-300 rounded-md p-3">
                  <div v-for="product in products" :key="product.id" class="flex items-center">
                    <input 
                      :id="`product-${product.id}`"
                      v-model="selectedProducts" 
                      :value="product.id" 
                      type="checkbox"
                      class="h-4 w-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900"
                    >
                    <label :for="`product-${product.id}`" class="ml-2 text-sm text-gray-700">
                      {{ product.name }} ({{ product.sku }})
                    </label>
                  </div>
                </div>
                <p class="mt-1 text-sm text-gray-500">选择适用的商品</p>
              </div>

              <div class="grid grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">总发放数量</label>
                  <input v-model.number="form.total_quantity" type="number" min="0"
                         class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                         placeholder="例如：100">
                  <p class="mt-1 text-sm text-gray-500">0表示无限制</p>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">每用户限领</label>
                  <input v-model.number="form.per_user_limit" type="number" min="0"
                         class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                         placeholder="例如：1">
                  <p class="mt-1 text-sm text-gray-500">0表示无限制</p>
                </div>
              </div>
            </div>
          </div>

          <!-- 有效期设置 -->
          <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-6">有效期设置</h3>
            
            <div class="grid grid-cols-1 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">开始时间</label>
                <input v-model="form.start_time" type="datetime-local"
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">结束时间</label>
                <input v-model="form.end_time" type="datetime-local"
                       class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent">
              </div>
            </div>
          </div>

          <!-- 其他设置 -->
          <div class="bg-white rounded-lg shadow-sm p-6">
            <h3 class="text-lg font-semibold text-gray-900 mb-6">其他设置</h3>
            
            <div class="space-y-4">
              <div class="flex items-center">
                <input v-model="form.stackable" type="checkbox" 
                       class="h-4 w-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900">
                <label class="ml-3 text-sm font-medium text-gray-700">可与其他优惠券叠加使用</label>
              </div>
              <div class="flex items-center">
                <input v-model="form.is_active" type="checkbox" 
                       class="h-4 w-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900">
                <label class="ml-3 text-sm font-medium text-gray-700">启用优惠券</label>
              </div>

              <div class="flex items-center">
                <input v-model="form.is_new_user_only" type="checkbox" 
                       class="h-4 w-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900">
                <label class="ml-3 text-sm font-medium text-gray-700">仅限新用户</label>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-end space-x-4">
            <Link :href="route('admin.coupons.index')" 
                  class="px-6 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900">
              取消
            </Link>
            <button type="submit" 
                    :disabled="isSubmitting"
                    class="px-6 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50">
              {{ isSubmitting ? '创建中...' : '创建优惠券' }}
            </button>
          </div>
        </form>
      </div>

      <!-- 右侧：实时预览 -->
      <div class="space-y-6">
        <div class="bg-white rounded-lg shadow-sm p-6">
          <h3 class="text-lg font-semibold text-gray-900 mb-6">实时预览</h3>
          
          <!-- 优惠券卡片预览 -->
          <div class="flex justify-center">
            <CouponCard 
              :coupon="previewCoupon"
              :action-type="'receive'"
              :show-action="false"
              class="max-w-sm"
            />
          </div>
          
          <!-- 优惠券详情 -->
          <div class="mt-6 space-y-4">
            <div class="border-t border-gray-200 pt-4">
              <h4 class="text-sm font-medium text-gray-900 mb-3">优惠券详情</h4>
              <dl class="grid grid-cols-1 gap-3 text-sm">
                <div class="flex justify-between">
                  <dt class="text-gray-500">优惠券名称</dt>
                  <dd class="text-gray-900">{{ form.name || '未设置' }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">优惠券代码</dt>
                  <dd class="text-gray-900 font-mono">{{ form.code || '未设置' }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">优惠券类型</dt>
                  <dd class="text-gray-900">{{ getTypeText(form.type) }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">优惠面值</dt>
                  <dd class="text-gray-900">{{ getValueText(form.type, form.value) }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">使用门槛</dt>
                  <dd class="text-gray-900">{{ getMinPurchaseText(form.min_purchase, form.type) }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">适用范围</dt>
                  <dd class="text-gray-900">{{ getApplicableText(form.applicable_type) }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">有效期</dt>
                  <dd class="text-gray-900">{{ getValidityText(form.start_time, form.end_time) }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">发放限制</dt>
                  <dd class="text-gray-900">{{ getQuantityText(form.total_quantity, form.per_user_limit) }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">叠加使用</dt>
                  <dd class="text-gray-900">{{ form.stackable ? '是' : '否' }}</dd>
                </div>
                <div class="flex justify-between">
                  <dt class="text-gray-500">状态</dt>
                  <dd class="text-gray-900">{{ form.is_active ? '启用' : '禁用' }}</dd>
                </div>
              </dl>
            </div>
          </div>
        </div>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Link, router, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import CouponCard from '@/Components/CouponCard.vue'

const props = defineProps({
  errors: {
    type: Object,
    default: () => ({})
  },
  categories: {
    type: Array,
    default: () => []
  },
  products: {
    type: Array,
    default: () => []
  }
})


const isSubmitting = ref(false)

// 选择器数据
const selectedCategories = ref([])
const selectedProducts = ref([])

const form = useForm({
  name: '',
  code: '',
  type: '',
  value: 0,
  max_discount: null,
  min_purchase: 0,
  applicable_type: 'all',
  applicable_ids: '',
  total_quantity: 0,
  per_user_limit: 0,
  start_time: '',
  end_time: '',
  stackable: false,
  is_active: true,
  is_new_user_only: false
})

// 预览优惠券数据
const previewCoupon = computed(() => ({
  id: 'preview',
  name: form.name || '优惠券名称',
  code: form.code || 'COUPON_CODE',
  type: form.type || 'fixed',
  value: form.value || 0,
  min_purchase: form.min_purchase || 0,
  max_discount: form.max_discount,
  usage_note: getUsageNote(),
  end_time: form.end_time || null,
  is_active: form.is_active
}))

const getValueDescription = (type) => {
  const descriptions = {
    fixed: '固定金额，单位：元',
    percent: '折扣百分比，例如：10表示10%',
    shipping: '包邮券，面值可为0',
    full_reduction: '满减券，面值表示满多少元'
  }
  return descriptions[type] || ''
}

const getTypeText = (type) => {
  const types = {
    fixed: '立减券',
    percent: '折扣券',
    shipping: '包邮券',
    full_reduction: '满减券'
  }
  return types[type] || '未选择'
}

const getValueText = (type, value) => {
  if (!type || !value) return '未设置'
  
  switch (type) {
    case 'fixed':
    case 'full_reduction':
      return `¥${value}`
    case 'percent':
      return `${value}折`
    case 'shipping':
      return '免运费'
    default:
      return '未设置'
  }
}

const getMinPurchaseText = (minPurchase, type) => {
  if (type === 'shipping') return '无门槛免运费'
  if (!minPurchase || minPurchase === 0) return '无门槛'
  return `满¥${minPurchase}可用`
}

const getApplicableText = (type) => {
  if (type === 'all') return '全场通用'
  if (type === 'category') {
    if (selectedCategories.value.length === 0) return '未选择分类'
    const categoryNames = selectedCategories.value.map(id => 
      props.categories.find(c => c.id === id)?.name || `ID:${id}`
    )
    return `指定分类: ${categoryNames.join(', ')}`
  }
  if (type === 'product') {
    if (selectedProducts.value.length === 0) return '未选择商品'
    const productNames = selectedProducts.value.map(id => 
      props.products.find(p => p.id === id)?.name || `ID:${id}`
    )
    return `指定商品: ${productNames.join(', ')}`
  }
  return '未选择'
}

const getValidityText = (startTime, endTime) => {
  if (!startTime && !endTime) return '永久有效'
  if (startTime && endTime) {
    return `${formatDateTime(startTime)} 至 ${formatDateTime(endTime)}`
  }
  if (startTime) return `从 ${formatDateTime(startTime)} 开始`
  if (endTime) return `至 ${formatDateTime(endTime)} 结束`
  return '未设置'
}

const getQuantityText = (total, perUser) => {
  const totalText = total === 0 ? '无限制' : `${total}张`
  const perUserText = perUser === 0 ? '无限制' : `${perUser}张`
  return `总计${totalText}，每用户${perUserText}`
}

const getUsageNote = () => {
  const notes = []
  
  if (form.min_purchase > 0) {
    notes.push(`满¥${form.min_purchase}可用`)
  }
  
  if (form.max_discount && form.type === 'percent') {
    notes.push(`最高优惠¥${form.max_discount}`)
  }
  
  if (form.applicable_type === 'category' && selectedCategories.value.length > 0) {
    const categoryNames = selectedCategories.value.map(id => 
      props.categories.find(c => c.id === id)?.name || `ID:${id}`
    )
    notes.push(`仅限分类: ${categoryNames.join(', ')}`)
  } else if (form.applicable_type === 'product' && selectedProducts.value.length > 0) {
    const productNames = selectedProducts.value.map(id => 
      props.products.find(p => p.id === id)?.name || `ID:${id}`
    )
    notes.push(`仅限商品: ${productNames.join(', ')}`)
  }
  
  if (form.stackable) {
    notes.push('可叠加使用')
  }
  
  return notes.join('，') || '无特殊说明'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const submitForm = () => {
  isSubmitting.value = true
  
  // 根据适用类型设置 applicable_ids
  let applicableIds = []
  if (form.applicable_type === 'category') {
    applicableIds = selectedCategories.value
  } else if (form.applicable_type === 'product') {
    applicableIds = selectedProducts.value
  }
  
  // 更新表单数据
  form.applicable_ids = applicableIds
  
    form.post(route('admin.coupons.store'), {
      onSuccess: () => {
        router.visit(route('admin.coupons.index'))
      },
      onFinish: () => {
        isSubmitting.value = false
      }
    })
}
</script>